<template>
	<view class="container">
	<view class="header">
		<text class="title">备件详情</text>
		<view class="more-btn" @click="showMoreOptions">
			<text class="more-icon">⋯</text>
		</view>
	</view>

		<view class="content" v-if="detail">
			<!-- 基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="info-grid">
					<view class="info-item">
						<text class="label">备件编号</text>
						<text class="value">{{ detail.partNo }}</text>
					</view>
					<view class="info-item">
						<text class="label">备件名称</text>
						<text class="value">{{ detail.name }}</text>
					</view>
					<view class="info-item">
						<text class="label">规格型号</text>
						<text class="value">{{ detail.specNo || '-' }}</text>
					</view>
					<view class="info-item">
						<text class="label">备件类型</text>
						<text class="value">{{ getTypeName(detail.partTypeCode) }}</text>
					</view>
					<view class="info-item">
						<text class="label">仓库</text>
						<text class="value">{{ getWarehouseName(detail.warehouseCode) }}</text>
					</view>
					<view class="info-item">
						<text class="label">库存总数</text>
						<text class="value">{{ detail.totalStock || 0 }}</text>
					</view>
				</view>
			</view>

			<!-- 关联资产 -->
			<view class="section" v-if="detail.assets && detail.assets.length > 0">
				<view class="section-title">关联资产</view>
				<view class="asset-list">
					<view class="asset-item" v-for="(asset, index) in detail.assets" :key="index" @click="viewAssetDetail(asset)">
						<view class="asset-info">
							<text class="asset-name">{{ asset.assetName }}</text>
							<text class="asset-no">{{ asset.assetNo }}</text>
							<text class="asset-location">{{ asset.location }}</text>
						</view>
						<text class="arrow">→</text>
					</view>
				</view>
			</view>

			<!-- 备件图片 -->
			<view class="section" v-if="detail.images && detail.images.length > 0">
				<view class="section-title">备件图片</view>
				<view class="image-list">
					<view class="image-item" v-for="(image, index) in detail.images" :key="index" @click="previewImage(index)">
						<image :src="image" class="part-image" mode="aspectFill"></image>
					</view>
				</view>
			</view>

			<!-- 操作记录 -->
			<view class="section">
				<view class="section-title">操作记录</view>
				<view class="record-list">
					<view class="record-item">
						<text class="record-time">创建时间</text>
						<text class="record-desc">{{ detail.createdAt || '-' }}</text>
					</view>
					<view class="record-item">
						<text class="record-time">更新时间</text>
						<text class="record-desc">{{ detail.updatedAt || '-' }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="!loading && !detail">
			<text class="empty-icon">📦</text>
			<text class="empty-text">备件信息不存在</text>
		</view>
	</view>
</template>

<script>
import { getPart, delPart } from '@/api/inventory/part.js'

export default {
	data() {
		return {
			partNo: '',
			detail: null,
			loading: true,
			// 备件类型映射
			typeMapping: {
				'BEARING': '轴承',
				'SEAL': '密封件',
				'FILTER': '过滤器',
				'BELT': '皮带',
				'CHAIN': '链条',
				'GEAR': '齿轮',
				'MOTOR': '电机',
				'PUMP': '泵',
				'VALVE': '阀门',
				'SENSOR': '传感器',
				'CONTROLLER': '控制器',
				'SWITCH': '开关',
				'CABLE': '电缆',
				'CONNECTOR': '连接器',
				'BOLT': '螺栓',
				'NUT': '螺母',
				'WASHER': '垫圈',
				'SPRING': '弹簧',
				'BUSHING': '衬套',
				'GASKET': '垫片'
			},
			// 仓库映射
			warehouseMapping: {
				'WH001': '主仓库',
				'WH002': '备用仓库',
				'WH003': '临时仓库',
				'MAIN': '主仓库',
				'BACKUP': '备用仓库',
				'TEMP': '临时仓库'
			}
		}
	},
	onLoad(options) {
		if (options.partNo) {
			this.partNo = options.partNo
			this.loadDetail()
		} else {
			uni.showToast({ title: '缺少备件编号', icon: 'none' })
			setTimeout(() => uni.navigateBack(), 1500)
		}
	},
	
	onShow() {
		// 每次显示页面时重新加载数据，确保显示最新信息
		if (this.partNo) {
			this.loadDetail()
		}
	},
	methods: {
		// 获取备件类型中文名称
		getTypeName(code) {
			return this.typeMapping[code] || code || '-'
		},
		
		// 获取仓库中文名称
		getWarehouseName(code) {
			return this.warehouseMapping[code] || code || '-'
		},
		
		async loadDetail() {
			try {
				this.loading = true
				const res = await getPart(this.partNo)
				console.log('备件详情API返回:', res)
				
				if (res && res.code === 200 && res.data) {
					const data = res.data
					console.log('原始API数据:', data)
					
					// 处理图片数据
					let images = []
					if (data.imageUrls) {
						try {
							if (typeof data.imageUrls === 'string') {
								images = JSON.parse(data.imageUrls)
							} else if (Array.isArray(data.imageUrls)) {
								images = data.imageUrls
							}
						} catch (e) {
							console.error('解析图片数据失败:', e)
						}
					}
					
					// 构建完整图片URL
					const minioBase = uni.getStorageSync('MINIO_BASE') || 'https://io.brightholdings.cn'
					const bucket = 'smart-maintenance'
					images = images.map(imageUrl => {
						if (!imageUrl) return '/static/banner-bg.jpg'
						if (/^https?:\/\//i.test(imageUrl)) return imageUrl
						return `${minioBase.replace(/\/$/, '')}/${bucket}/${imageUrl}`
					})
					
					// 处理关联资产数据
					let assets = []
					if (data.associatedAssetsJson) {
						try {
							if (typeof data.associatedAssetsJson === 'string') {
								assets = JSON.parse(data.associatedAssetsJson)
							} else if (Array.isArray(data.associatedAssetsJson)) {
								assets = data.associatedAssetsJson
							}
						} catch (e) {
							console.error('解析关联资产数据失败:', e)
						}
					}
					
					// 处理字段映射，使用PartDTO的字段名
					this.detail = {
						partNo: data.partNo,
						name: data.partName, // PartDTO中name字段映射为partName
						specNo: data.specNo,
						partTypeName: data.partTypeName,
						partTypeCode: data.partTypeCode, // 保存编码用于显示
						warehouseName: data.warehouseName,
						warehouseCode: data.warehouseCode, // 保存编码用于显示
						totalStock: data.stockTotal || 0,
						images: images,
						assets: assets,
						createdAt: data.createdAt,
						updatedAt: data.updatedAt
					}
					
					console.log('处理后的详情数据:', this.detail)
				} else {
					uni.showToast({ title: res.msg || '获取备件详情失败', icon: 'none' })
				}
			} catch (e) {
				console.error('加载备件详情失败:', e)
				uni.showToast({ title: '加载失败', icon: 'none' })
			} finally {
				this.loading = false
			}
		},
		
		goBack() {
			uni.navigateBack()
		},
		
		showMoreOptions() {
			uni.showActionSheet({
				itemList: ['编辑', '删除', '复制编号'],
				success: (res) => {
					switch (res.tapIndex) {
						case 0:
							this.editPart()
							break
						case 1:
							this.deletePart()
							break
						case 2:
							this.copyPartNo()
							break
					}
				}
			})
		},
		
		editPart() {
			uni.navigateTo({
				url: `/pages/spare-parts/edit?partNo=${this.partNo}`
			})
		},
		
		async deletePart() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个备件吗？删除后无法恢复。',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({ title: '删除中...' })
							const result = await delPart(this.partNo)
							uni.hideLoading()
							
						if (result && result.code === 200) {
							uni.showToast({ title: '删除成功', icon: 'success' })
							// 设置标记，通知台账页面需要刷新
							uni.setStorageSync('needRefreshLedger', true)
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						} else {
								uni.showToast({ title: result.msg || '删除失败', icon: 'none' })
							}
						} catch (e) {
							uni.hideLoading()
							console.error('删除备件失败:', e)
							uni.showToast({ title: '删除失败: ' + (e.message || '未知错误'), icon: 'none' })
						}
					}
				}
			})
		},
		
		copyPartNo() {
			uni.setClipboardData({
				data: this.partNo,
				success: () => {
					uni.showToast({ title: '已复制到剪贴板', icon: 'success' })
				}
			})
		},
		
		viewAssetDetail(asset) {
			uni.navigateTo({
				url: `/pages/asset/detail?assetNo=${asset.assetNo}`
			})
		},
		
		previewImage(index) {
			const urls = this.detail.images
			uni.previewImage({
				current: index,
				urls: urls
			})
		}
	}
}
</script>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f5f6f7;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.more-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.more-icon {
	font-size: 36rpx;
	color: #333;
}

.title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.content {
	padding: 20rpx;
}

.section {
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	padding: 30rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.info-grid {
	padding: 20rpx 30rpx 30rpx;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f8f8f8;
}

.info-item:last-child {
	border-bottom: none;
}

.label {
	font-size: 28rpx;
	color: #666;
}

.value {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.asset-list {
	padding: 20rpx 30rpx 30rpx;
}

.asset-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f8f8f8;
}

.asset-item:last-child {
	border-bottom: none;
}

.asset-info {
	flex: 1;
}

.asset-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
	margin-bottom: 8rpx;
}

.asset-no {
	font-size: 24rpx;
	color: #666;
	display: block;
	margin-bottom: 4rpx;
}

.asset-location {
	font-size: 24rpx;
	color: #999;
	display: block;
}

.arrow {
	font-size: 24rpx;
	color: #ccc;
}

.image-list {
	padding: 20rpx 30rpx 30rpx;
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.image-item {
	width: 200rpx;
	height: 200rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.part-image {
	width: 100%;
	height: 100%;
}

.record-list {
	padding: 20rpx 30rpx 30rpx;
}

.record-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f8f8f8;
}

.record-item:last-child {
	border-bottom: none;
}

.record-time {
	font-size: 28rpx;
	color: #666;
}

.record-desc {
	font-size: 28rpx;
	color: #333;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}
</style>
